"use strict";

const Controller = require("egg").Controller;

class ProductController extends Controller {
  // 查询商品列表
  async list() {
    const { ctx } = this;
    const query = ctx.query;
    query.userId=ctx.getUserId();
    const result = await ctx.service.product.query(query);
    ctx.success("成功", result);
  }
  // 新增商品
  async add() {
    const { ctx } = this;
    const { name, price, desc } = ctx.request.body;
    const userId=ctx.getUserId();
    ctx.validate({
      name: { type: "string", min: 3, max: 50, message:'aaaa' },
      price: { type: "number", min: 0, max: 99999 },
      desc: { type: "string", required: false },
    });
    const result = await ctx.service.product.add({ name, price, desc,userId });
    ctx.success(result);
  }
  // 查询商品详情
  async detail() {
    const { ctx } = this;
    const { id } = ctx.params;
    const rules = {
      id: { type: "id" },
    };
    ctx.validate(
      rules,
      ctx.params
    );
    const result = await ctx.service.product.detail(id);
    ctx.success("查询成功", result);
  }
  // 更新商品信息
  async update() {
    const { ctx } = this;
    const { name, price, desc } = ctx.request.body;
    const { id } = ctx.params;
    const rules = {
      name: { type: "string", min: 3, max: 50 },
      price: { type: "number", min: 0, max: 99999 },
      desc: { type: "string", required: false },
    };
    ctx.validate(rules);
    const result = await ctx.service.product.update(id, {
      name,
      price,
      desc,
    });
    ctx.success(result);
  }
  // 删除商品
  async delete() {
    const { ctx } = this;
    const { id } = ctx.params;
    const rules = {
      id: { type: "id" },
    };
    ctx.validate(
      rules,
      ctx.params
    );
    const result = await ctx.service.product.delete(id);
    ctx.success(result);

  }
}

module.exports = ProductController;
